/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NuevoPrivilegio.java
 *
 * Created on 11-ene-2013, 9:29:43
 */
package inscripciones.vista;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.beansbinding.BindingGroup;
import inscripciones.DAO.ConsultasBD;
import inscripciones.ModeloDAO.PrivilegioUsuarioDAO;
import inscripciones.Utiles.Mensajes;
import inscripciones.modelo.PrivilegioUsuario;

/**
 *
 * @author DJ2-PC
 */
public class NuevoPrivilegio extends javax.swing.JDialog {

    PrivilegioUsuario privilegio;
    BindingGroup b;
    ArrayList<PrivilegioUsuario> privilegios;

    /** Creates new form NuevoPrivilegio */
    public NuevoPrivilegio(java.awt.Frame parent, boolean modal, BindingGroup b, ArrayList<PrivilegioUsuario> privilegios) {
        super(parent, modal);
        this.privilegio = new PrivilegioUsuario();
        this.privilegios = privilegios;
        this.b = b;
        initComponents();
        long c = new ConsultasBD().ContadorRegistros("PrivilegioUsuario", "id");
        jcbTotal.setSelectedIndex(0);
        if(c==0){
            jcbTotal.setEnabled(false);
        }else{
            jcbTotal.setEnabled(true);
        }

    }

    public NuevoPrivilegio(java.awt.Frame parent, boolean modal, BindingGroup b, PrivilegioUsuario privilegio) {
        super(parent, modal);
        this.privilegio = privilegio;
        this.b = b;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        imagePanel1 = new com.mycsistemas.swingec.panel.ImagePanel();
        curvesPanel1 = new com.mycsistemas.swingec.panel.CurvesPanel();
        jLblPrivilegio = new javax.swing.JLabel();
        jLblNombre = new javax.swing.JLabel();
        jTxtNombre = new javax.swing.JTextField();
        jBtnAceptar = new javax.swing.JButton();
        jBtnCancelar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jcbTotal = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        imagePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/inscripciones/Recursos/''_10102012_1738.jpeg"))); // NOI18N
        imagePanel1.setLayout(null);

        curvesPanel1.setLayout(null);

        jLblPrivilegio.setFont(new java.awt.Font("Georgia", 3, 18));
        jLblPrivilegio.setForeground(new java.awt.Color(255, 255, 255));
        jLblPrivilegio.setText("Privilegio");
        curvesPanel1.add(jLblPrivilegio);
        jLblPrivilegio.setBounds(93, 25, 194, 21);

        jLblNombre.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblNombre.setForeground(new java.awt.Color(255, 255, 255));
        jLblNombre.setText("Acceso:");
        curvesPanel1.add(jLblNombre);
        jLblNombre.setBounds(20, 100, 50, 18);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${privilegio.nombre}"), jTxtNombre, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        curvesPanel1.add(jTxtNombre);
        jTxtNombre.setBounds(90, 60, 194, 30);

        jBtnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/inscripciones/Recursos/tick_32.png"))); // NOI18N
        jBtnAceptar.setText("Aceptar");
        jBtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        curvesPanel1.add(jBtnAceptar);
        jBtnAceptar.setBounds(40, 150, 121, 40);

        jBtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/inscripciones/Recursos/DeleteRed.png"))); // NOI18N
        jBtnCancelar.setText("Cancelar");
        jBtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        curvesPanel1.add(jBtnCancelar);
        jBtnCancelar.setBounds(170, 150, 120, 40);

        jLabel3.setFont(new java.awt.Font("Elephant", 0, 14));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Nombre:");
        curvesPanel1.add(jLabel3);
        jLabel3.setBounds(22, 64, 61, 18);

        jcbTotal.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TOTAL", "PARCIAL" }));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${privilegio.acceso}"), jcbTotal, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        curvesPanel1.add(jcbTotal);
        jcbTotal.setBounds(90, 100, 190, 30);

        imagePanel1.add(curvesPanel1);
        curvesPanel1.setBounds(0, 0, 310, 210);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    if (jTxtNombre.getText().length() == 0) {
        dispose();
    } else {
        if (new Mensajes().ConfirmacionDialogowarning(this, "¿Desea Salir sin Guardar el Registro Actual?") == 0) {
            this.dispose();
        }
    }
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    if (validarCampos()) {
        //llenarCampos(privilegio)        
        privilegio.setAcceso(jcbTotal.getSelectedItem().toString());
        PrivilegioUsuarioDAO pdao = new PrivilegioUsuarioDAO(privilegio);

        if (privilegio.getId() == null) {
            if (existePrivilegioNuevo()) {
                try {
                    pdao.persist();
                    new Mensajes().StandarTick(this, "Agregado Con Éxito");
                    b.unbind();
                    privilegios.add(privilegio);
                    b.bind();
                    this.dispose();
                } catch (Exception ex) {
                    Logger.getLogger(NuevoPrivilegio.class.getName()).log(Level.SEVERE, null, ex);
                    new Mensajes().StandarWarning(this, "El Registro no se Guardó");
                }
            }else{
                new Mensajes().StandarWarning(this, "    No es posible guardar. \n Ya Existe un Registro con ese Nombre ");                
            }
        } else {
            if(existePrivilegioActualizar()){
                try {
                pdao.update();
                b.unbind();
                b.bind();
                new Mensajes().StandarTick(this, "Actualizado Con Éxito");
                this.dispose();
            } catch (Exception ex) {
                Logger.getLogger(NuevoPrivilegio.class.getName()).log(Level.SEVERE, null, ex);
                new Mensajes().StandarWarning(this, "El Registro no se Actualizó");
            }
            }else{
                new Mensajes().StandarWarning(this, "    No se puede actualizar. \n Ya existe otro Privilegio con ese Nombre");
            }       
        }
    } else {
        new Mensajes().StandarWarning(this, "Ingrese Todos los Campos");
    }

}//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public PrivilegioUsuario getPrivilegio() {
        return privilegio;
    }

    public void setPrivilegio(PrivilegioUsuario privilegio) {
        this.privilegio = privilegio;
    }

    private boolean validarCampos() {
        if (!jTxtNombre.getText().isEmpty()) {
            if (!jcbTotal.getSelectedItem().toString().isEmpty()) {
                return true;
            }
        }
        return false;
    }

    private boolean existePrivilegioNuevo() {
        ArrayList<PrivilegioUsuario> privilegs = (ArrayList<PrivilegioUsuario>) new ConsultasBD().buscarPOR("PrivilegioUsuario", "nombre", "'"+jTxtNombre.getText()+"'");
        if (privilegs.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
    
    private boolean existePrivilegioActualizar() {
        ArrayList<PrivilegioUsuario> privilegs = (ArrayList<PrivilegioUsuario>) new ConsultasBD().buscarExcepto("PrivilegioUsuario","id", String.valueOf(privilegio.getId()) ,"nombre", "'"+String.valueOf(privilegio.getNombre())+"'");
        if (privilegs.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.mycsistemas.swingec.panel.CurvesPanel curvesPanel1;
    private com.mycsistemas.swingec.panel.ImagePanel imagePanel1;
    private javax.swing.JButton jBtnAceptar;
    private javax.swing.JButton jBtnCancelar;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLblNombre;
    private javax.swing.JLabel jLblPrivilegio;
    private javax.swing.JTextField jTxtNombre;
    private javax.swing.JComboBox jcbTotal;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
